<template>
  <el-main>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item>
        公寓名称
        <el-input v-model="ruleForm.flagName" style="width: 15%;margin-right: 50px"></el-input>
        楼盘名称
        <el-input v-model="ruleForm.name" style="width: 15%;margin-right: 50px"></el-input>
        <el-link href="http://localhost/house/add" type="primary" style="margin-right: 20px">添加楼盘</el-link>
      </el-form-item>
      <el-form-item>
        公共配套
        <el-checkbox-group v-model="publicIds">
          <el-checkbox v-for="item in publicFacilitys" :label="item.id" :value="item.id">{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        公共区域照片
        <div>
          <el-upload
            class="upload-demo"
            drag
            :limit="1"
            :before-upload="handleBeforeUploadVideo"
            :http-request="requestFile"
            :on-remove="removeFile"
            action="">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <!-- 进度条 -->
          <el-progress  v-if="progressFlag" :percentage="loadProgress"></el-progress>
          <el-button id="myBtn" v-if="progressFlag" size="mini">{{buttonText}}</el-button>
        </div>
      </el-form-item>
      <el-form-item>
        付款方式:押
        <el-select v-model="ruleForm.paymentMortgage" style="width: 6%">
          <el-option v-for="item in this.ids" :value="item"></el-option>
        </el-select>
        付
        <el-select v-model="ruleForm.paymentPay" style="width: 6%">
          <el-option v-for="item in this.ids" :value="item"></el-option>
        </el-select>
        <span style="margin-left: 10%">户型</span>
        <el-select v-model="ruleForm.room" style="width: 6%">
          <el-option v-for="item in this.ids" :value="item"></el-option>
        </el-select>
        室
        <el-select v-model="ruleForm.hall" style="width: 6%">
          <el-option v-for="item in this.ids" :value="item"></el-option>
        </el-select>
        厅
      </el-form-item>
      <el-form-item>
        <span>装修情况</span>
        <el-select v-model="ruleForm.decorate" style="width: 6%;">
          <el-option label="精装" value="0"></el-option>
          <el-option label="简装" value="1"></el-option>
          <el-option label="毛坯" value="2"></el-option>
        </el-select>
        <span style="margin-left: 10%">设置管家</span>
        <el-select v-model="ruleForm.manager">
          <el-option v-for="item in manager" :label="item.username" :value="item.userId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        房源介绍<textarea v-model="ruleForm.introduce" style="width: 1000px;height: 80px"></textarea>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addRoom">添加房型</el-button>
      </el-form-item>
      <el-form-item style="margin-left: 30%;">
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="房型名称">
          <el-input v-model="form.acreage"></el-input>
        </el-form-item>
        <el-form-item label="面积">
          <el-input v-model="form.proportion" style="width: 90%"></el-input>平方米
        </el-form-item>
        <el-form-item label="朝向">
          <el-select v-model="form.direction">
            <el-option value="1" label="东"></el-option>
            <el-option value="2" label="南"></el-option>
            <el-option value="3" label="西"></el-option>
            <el-option value="4" label="北"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="独立配套">
          <el-checkbox-group v-model="privateIds">
            <el-checkbox v-for="item in privateFacilitys" :label="item.id" :value="item.id">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="租金">
          <el-input v-model="form.rental" style="width: 90%;"></el-input>元/月
        </el-form-item>
        <el-form-item label="房间区域">
          <div>
            <el-upload
              class="upload-demo"
              drag
              :limit="1"
              :before-upload="handleBeforeUploadVideo"
              :http-request="requestFile1"
              :on-remove="removeFile"
              action="">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
            <!-- 进度条 -->
            <el-progress  v-if="progressFlag1" :percentage="loadProgress1"></el-progress>
            <el-button id="myBtn" v-if="progressFlag1" size="mini">{{buttonText1}}</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addHouse">确认保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-main>
</template>

<script>
import { getPrivateFacility,getPublicFacility,getManager,saveCentralization } from "@/api/system/info";
import {getUpToken} from "@/api/file/upload";
import {v4 as uuidv4} from "uuid";
import * as qiniu from "qiniu-js";

export default {
  name: "saveCentralization",
  data() {
    return {
      privateFacilitys:[],
      publicFacilitys:[],
      manager:[],
      dialogVisible:false,
      privateIds:[],
      publicIds:[],
      ids: [1, 2, 3, 4, 5],
      form:{roomPicture:''},
      fileName:'',
      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条
      buttonText: "暂停上传",
      loadProgress1: 0, // 动态显示进度条
      progressFlag1: false, // 关闭进度条
      buttonText1: "暂停上传",
      upToken:null,
      images:null,
      domainAddress:'http://rcdkvzv4v.hn-bkt.clouddn.com/',
      ruleForm: {
        housePictureUrl: '',
        roomPictureUrl: '',
      },
      rules: {
        name: [
          {required: true, message: '请输入活动名称', trigger: 'blur'},
          {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
      }
    }
  },
  methods: {
    addHouse() {
      this.ruleForm.roomName = this.form.roomName;
      this.ruleForm.acreage=this.form.acreage;
      this.ruleForm.proportion = this.form.proportion;
      this.ruleForm.direction = this.form.direction;
      this.ruleForm.privateIds = this.privateIds;
      this.ruleForm.rental = this.form.rental;
      this.ruleForm.roomPicture = this.form.roomPicture;
      this.dialogVisible=false;
    },
    submitForm() {
      if(this.ruleForm.name==null){
        alert("请选择楼盘名称")
      }else {
        this.ruleForm.publicIds = this.publicIds;
        this.ruleForm.privateIds = this.privateIds;
        this.ruleForm.type=1;
        saveCentralization(this.ruleForm).then(res => {
          if(res.code==200){
            this.$message.success("添加成功")
            window.location.href="http://localhost/roomInfo";
          }else {
            this.$message.error(res.msg);
          }
        })
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    addRoom() {
      this.dialogVisible=true;
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    handleAvatarSuccess(res) {
      this.ruleForm.housePicture = res;
    },
    handleAvatarSuccess2(res) {
      this.form.roomPicture = res;
    },
    getPrivateFacility() {
      getPrivateFacility().then(res=>{
        this.privateFacilitys=res.data;
      })
    },
    getPublicFacility() {
      getPublicFacility().then(res=>{
        this.publicFacilitys=res.data;
      })
    },
    getManager() {
      getManager().then(res=>{
        this.manager=res.data;
      })
    },
    //移除文件
    removeFile() {
      this.progressFlag = false;
      this.buttonText = "暂停上传";
    },
    //上传之前
    handleBeforeUploadVideo(file) {
      //上传之前重新获取uptoken以免过期
      // console.log(file)
      this.progressFlag = true;
    },
    getUp(){
      getUpToken().then(res=>{
        this.upToken = res;
        console.log("后台获取token--",this.upToken);
      });
    },
    //
    uploadWithSDK(token,putExtra,config,domain,file) {
      let that = this;
      console.log("token,",token);
      console.log("putExtra,",putExtra);
      console.log("config,",config);
      console.log("domain,",domain);
      console.log("file,",file);
      if (file) {
        let key =uuidv4() + file.name;
        // putExtra.customVars["x:name"] = key.split(".")[0];
        // 设置next,error,complete对应的操作，分别处理相应的进度信息，错误信息，以及完成后的操作
        let error = function(err) {
          console.log(err);
        };

        let complete = function(res) {
          console.log(res);
          that.fileName =that.domainAddress + res.key;
          that.ruleForm.housePictureUrl = that.fileName;
          console.log(that.fileName);
        };

        let next = function(response) {
          console.log(response);
          that.loadProgress = response.total.percent;
        };

        let subObject = {
          next: next,
          error: error,
          complete: complete
        };
        // 调用sdk上传接口获得相应的observable，控制上传和暂停
        let observable = qiniu.upload(file, key, token, putExtra, config);
        let subscription = observable.subscribe(subObject);

        //监听按钮事件，控制上传
        that.$nextTick(function () {
          document.getElementById("myBtn").addEventListener("click", function(){
            console.log("1111111111111111111111111111111111111111")
            if(that.buttonText == "暂停上传"){
              that.buttonText = "继续上传";
              subscription.unsubscribe();
            }else if(that.buttonText = "继续上传"){
              that.buttonText = "暂停上传";
              subscription = observable.subscribe(subObject);
            }
          });
        })

      }

    },
    requestFile(param) {
      console.log("request,",param)
      let file = param.file;
      //uptoken
      let token = this.upToken;
      //外链域名
      let domain = this.domainAddress;
      //可以配置分片大小等配置，具体查看官方文档
      let config = {
        useCdnDomain: false,//是否使用CDN加速域名
        disableStatisticsReport: false,//是否禁用日志报告
        retryCount: 6,//上传自动重试次数
        chunkSize: "4"// 每片大小
      };
      let putExtra = {
        customVars: {}
      };
      this.uploadWithSDK(token,putExtra,config,domain,file)
    },
    uploadWithSDK1(token,putExtra,config,domain,file) {
      let that = this;
      console.log("token,",token);
      console.log("putExtra,",putExtra);
      console.log("config,",config);
      console.log("domain,",domain);
      console.log("file,",file);
      if (file) {
        let key =uuidv4() + file.name;
        // putExtra.customVars["x:name"] = key.split(".")[0];
        // 设置next,error,complete对应的操作，分别处理相应的进度信息，错误信息，以及完成后的操作
        let error = function(err) {
          console.log(err);
        };

        let complete = function(res) {
          console.log(res);
          that.fileName =that.domainAddress + res.key;
          that.form.roomPictureUrl = that.fileName;
          console.log(that.fileName);
        };

        let next = function(response) {
          console.log(response);
          that.loadProgress1 = response.total.percent;
        };

        let subObject = {
          next: next,
          error: error,
          complete: complete
        };
        // 调用sdk上传接口获得相应的observable，控制上传和暂停
        let observable = qiniu.upload(file, key, token, putExtra, config);
        let subscription = observable.subscribe(subObject);

        //监听按钮事件，控制上传
        that.$nextTick(function () {
          document.getElementById("myBtn").addEventListener("click", function(){
            console.log("1111111111111111111111111111111111111111")
            if(that.buttonText1 == "暂停上传"){
              that.buttonText1 = "继续上传";
              subscription.unsubscribe();
            }else if(that.buttonText1 = "继续上传"){
              that.buttonText1 = "暂停上传";
              subscription = observable.subscribe(subObject);
            }
          });
        })

      }

    },
    requestFile1(param) {
      console.log("request,",param)
      let file = param.file;
      //uptoken
      let token = this.upToken;
      //外链域名
      let domain = this.domainAddress;
      //可以配置分片大小等配置，具体查看官方文档
      let config = {
        useCdnDomain: false,//是否使用CDN加速域名
        disableStatisticsReport: false,//是否禁用日志报告
        retryCount: 6,//上传自动重试次数
        chunkSize: "4"// 每片大小
      };
      let putExtra = {
        customVars: {}
      };
      this.uploadWithSDK1(token,putExtra,config,domain,file)
    }
  },
  created() {
    this.getPrivateFacility();
    this.getPublicFacility();
    this.getManager();
    this.getUp();
  }
}
</script>

<style scoped>

</style>
